package com.starsea.book.ui.newpage.normalview

import android.content.Context
import android.util.AttributeSet
import android.widget.LinearLayout
import com.starsea.book.ui.newpage.normalview.delegate.RadiusViewDelegate

class RadiusLinearLayout @JvmOverloads constructor(context: Context?, attrs: AttributeSet? = null) :
  LinearLayout(context, attrs) {
  /**
   * 获取代理类用于Java代码控制shape属性
   *
   * @return
   */
  val delegate: RadiusViewDelegate?

  init {
    delegate = RadiusViewDelegate(this, context!!, attrs)
  }

  override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
    if (delegate != null && delegate.widthHeightEqualEnable && width > 0 && height > 0) {
      val max = Math.max(width, height)
      val measureSpec = MeasureSpec.makeMeasureSpec(max, MeasureSpec.EXACTLY)
      super.onMeasure(measureSpec, measureSpec)
      return
    }
    super.onMeasure(widthMeasureSpec, heightMeasureSpec)
  }

  override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
    super.onLayout(changed, left, top, right, bottom)
    if (delegate != null) {
      if (delegate.radiusHalfHeightEnable) {
        delegate.setRadius((height / 2).toFloat())
      }
      delegate.init()
    }
  }

  override fun setSelected(selected: Boolean) {
    super.setSelected(selected)
    delegate?.setSelected(selected)
  }

  override fun setEnabled(enabled: Boolean) {
    super.setEnabled(enabled)
    delegate?.init()
  }
}